//
//  SendMsgToolView.swift
//  test_Huanxin
//
//  Created by alyadan on 2016/12/2.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import MVVM_BaseViewController
import SnapKit
import RxSwift
import RxCocoa
import YD_ProgressHUD

class SendMsgToolView: UIView , UITextViewDelegate{
    override var currentModel: SendMsgToolViewModel{
       return viewModel.value as! SendMsgToolViewModel
    }
    
    
    let inputTextView = UITextView()
    
    let sendBtn = UIButton(type: .custom)
    
    
    override func setupUI() {
        super.setupUI()
        backgroundColor = UIColor(HEXValue: 0xf0f0f0)
        
        
        addSubview(inputTextView)
        
        inputTextView.returnKeyType = .send
        inputTextView.layer.cornerRadius = 3
        inputTextView.delegate = self
        inputTextView.layer.borderColor = UIColor.init(HEXValue: 0xa0a0a0).cgColor
        inputTextView.layer.borderWidth = 0.5
        inputTextView.isScrollEnabled = false
        inputTextView.font = UIFont.systemFont(ofSize: 14)
        inputTextView.textContainerInset = UIEdgeInsetsMake(8, 7, 7, 7)
        
        
        addSubview(sendBtn)
        sendBtn.setTitle("发送", for: .normal)
        sendBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        sendBtn.setTitleColor(UIColor.black, for: .normal)
        
    }
    
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        let newLines = NSCharacterSet.newlines
        let rang = text.rangeOfCharacter(from: newLines)
        if rang != nil {
            self.sendMsg()
        }
        
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {
        let width = textView.frame.width
        let newSize = textView.sizeThatFits(CGSize.init(width: width, height: CGFloat(MAXFLOAT)))
        var newHeight = newSize.height
        
        if newHeight <= 35 {
            newHeight = 35
        }
        
        if newHeight != textView.frame.height {
            
            textView.snp.updateConstraints { (ConstraintMaker) in
                ConstraintMaker.height.equalTo(newHeight)
            }
            
        }
        
    }
    
    
    let btnWidth = 30
    let viewGap = 8
    override func updateConstraints() {
        
        
        inputTextView.snp.updateConstraints {[unowned self] (ConstraintMaker) in
            ConstraintMaker.left.equalTo(self).offset(self.viewGap)
            ConstraintMaker.centerY.equalTo(self)
            ConstraintMaker.height.equalTo(35)
            ConstraintMaker.top.equalTo(self).offset(5)
            ConstraintMaker.bottom.equalTo(self).offset(-5)
        }
        
        
        sendBtn.snp.updateConstraints {[unowned self] (ConstraintMaker) in
            ConstraintMaker.left.equalTo(self.inputTextView.snp.right).offset(self.viewGap)
            ConstraintMaker.centerY.equalTo(self.inputTextView)
            ConstraintMaker.height.equalTo(self.inputTextView)
            ConstraintMaker.width.equalTo(40)
            ConstraintMaker.right.equalTo(self).offset( -(self.viewGap / 2))
        }
        
        super.updateConstraints()
    }
    
    
    override func bindModelData() {
        
        currentModel.placeHolder.asDriver()
            .drive(inputTextView.placeHolder().rx.text)
            .addDisposableTo(disposeBag)
        
        inputTextView.rx.text
            .bindNext {[unowned self] (x:String?) in
                if let x = x {
                    self.currentModel.text.value = x
                }
            }
            .addDisposableTo(disposeBag)
        
        currentModel.text
            .asDriver()
            .drive(inputTextView.rx.text)
            .addDisposableTo(disposeBag)
        
        
        
    }
    
    override func addActionTarget() {
       sendBtn.rx.tap
        .bindNext {[unowned self] in
            self.sendMsg()
        }
        .addDisposableTo(disposeBag)
    }
    
    
    func sendMsg(){
        
        var text = inputTextView.text!
        text = text.trimmingCharacters(in: CharacterSet.whitespaces)
        if text.characters.count > 0{
            self.currentModel.sendMsgBlock?(text)
        }else{
           YD_HUDCenter.share.svpHud.showMessage(message: "不能发送空白消息")
        }
        inputTextView.text = ""
        currentModel.placeHolder.value = currentModel.firstPlaceHolder
        inputTextView.resignFirstResponder()
        
    }
}


public class SendMsgToolViewModel: MVVM_BaseViewModel {
    
    
    public typealias SendMsgCallBack = (String) -> Void
    
    public var placeHolder = Variable<String>("")
    
    public var text = Variable<String>("")
    
    
    var firstPlaceHolder = ""
    
    public var sendMsgBlock: SendMsgCallBack?
    
    
    override public func setupModel() {
       placeHolder.asObservable()
        .filter{$0.characters.count > 0}
        .take(1)
        .bindNext { [unowned self] (x:String) in
           self.firstPlaceHolder = x
        }
        .addDisposableTo(disposeBag)
    }
    
    
}

var textViewPlaceHolder:Int = 0
extension UITextView{
    
    func placeHolder() -> UILabel {
       var label = objc_getAssociatedObject(self, &textViewPlaceHolder) as? UILabel
        
        if label == nil {
            let x  = UILabel()
            label = x
            addSubview(x)
            x.textColor = UIColor.lightGray
            self.rx.observeWeakly(UIFont.self, "font")
                .bindNext({ (font:UIFont?) in
                   x.font = font
            })
            .addDisposableTo(disposeBag)
            
        
            x.snp.makeConstraints({[unowned self] (ConstraintMaker) in
                ConstraintMaker.left.equalTo(self).offset(10)
                ConstraintMaker.centerY.equalTo(self)
            })
            
            
            self.rx.text.map({ (x:String?) -> Bool in
                if let x = x {
                   return x.characters.count != 0
                }
                return true
            })
            .subscribe(x.rx.isHidden)
            .addDisposableTo(disposeBag)
            objc_setAssociatedObject(self, &textViewPlaceHolder, x, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            
        }
        
        return label!
    }
    
}


